const { defineConfig } = require('@vue/cli-service');
const { VantResolver } = require('unplugin-vue-components/resolvers');
const ComponentsPlugin = require('unplugin-vue-components/webpack');
const path = require('path');
const pkg = require('./package.json');
const envConfig = require('./env.config');

const outputDir = 'dist';
const NODE_ENV = process?.env?.NODE_ENV;
const VUE_APP_ENV = process?.env?.VUE_APP_ENV;
const publicPath = envConfig[NODE_ENV][`VUE_APP_${VUE_APP_ENV.toUpperCase()}_PUBLIC_PATH`];

process.env.VUE_APP_CONFIG = JSON.stringify(envConfig[NODE_ENV]);
process.env.VUE_APP_VIEWPORT_WIDTH = JSON.stringify(375);
process.env.VUE_APP_VERSION = JSON.stringify(pkg.version);

function resolve(dir) {
  return path.join(__dirname, dir);
}

module.exports = defineConfig({
  publicPath,
  outputDir,
  assetsDir: `static/${pkg.version}`,
  transpileDependencies: true,
  filenameHashing: true,
  devServer: {
    client: {
      overlay: {
        errors: false,
      },
    },
    proxy: {
      '/testapi': {
        target: 'https://ttapi.cfmoto-oversea.com/v1.0',
        changeOrigin: true,
        pathRewrite: { '^/testapi': '' },
      },
      '/api': {
        target: 'https://tapi.cfmoto-oversea.com/v1.0',
        changeOrigin: true,
        pathRewrite: { '^/api': '' },
      },
    },
  },
  configureWebpack: {
    plugins: [
      ComponentsPlugin({
        resolvers: [VantResolver()],
      }),
    ],
  },
  chainWebpack: (webpackConfig) => {
    webpackConfig.plugin('html').tap((args) => {
      // const mobLinks = { PRODUCTION: `<script src="//a23d.t4m.cn/applink.js"></script>`, TEST: `<script src="//a23e.t4m.cn/applink.js"></script>` };
      const vconsoleSrc = '//oss-int.zeehoev.com/pkg/vconsole%403.15.1/dist/vconsole.min.js';
      const vconsole = NODE_ENV === 'production' && VUE_APP_ENV === 'production' ? '' : `<script src="${vconsoleSrc}"></script>`;
      args[0].title = pkg.title;
      args[0].keywords = pkg.keywords.join('、');
      args[0].description = pkg.description;
      args[0].script = { vconsole };
      return args;
    });

    // set svg-sprite-loader
    webpackConfig.module.rule('svg').exclude.add(resolve('src/icons')).end();
    webpackConfig.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end();
  },
});
